﻿using System;

namespace DnDEngine.WebEngine
{
    public class RequestEngine
    {
        #region "Private attributes"

        private System.Net.WebResponse _response;
        private Class.Request _currentRequest;

        #endregion

        #region "Properties"

        public Class.Request CurrentRequest
        {
            get { return _currentRequest; }
        }

        public System.Net.WebResponse Response
        {
            get { return _response; }
        }

        public Double TimeElapSed()
        {
            return Tools.Chrono.GetElpasedTime("RequestEngine");
            ;
        }
        
        #endregion

        #region "Event"
        //Delegate 
        public delegate void RequestEngineEventHandler();
        public delegate void RequestEngineErrorHandler(String error);


        //Event
        public event RequestEngineEventHandler ResponseOk;
        public event RequestEngineErrorHandler ResponseError;
        #endregion

        #region "Public functions"

        public RequestEngine()
        {
          
        }

        public void GetAsyncResponse(Class.Request req)
        {
            try
            {
                Logger.Log.TraceAction("RequestEngine.GetAsyncResponse", "");
                _currentRequest = req;
                var AsyncReq = HttpRequestBuilder.HttpRequestFactory(req.GetRequestWithParams(), req.Method);
                var thread = new System.Threading.Thread(AsyncResponse);
                Tools.Chrono.Start("RequestEngine");
                thread.Start(AsyncReq);
            }
            catch (System.Exception ex)
            {
                Logger.Log.TraceError("RequestEngine.GetAsyncResponse", ex);
            }
        }

        #endregion

        #region "Private functions"

        private void AsyncResponse(object obj)
        {
            try
            {
                Logger.Log.TraceAction("RequestEngine.AsyncResponse", "");
                _response = ((System.Net.HttpWebRequest)obj).GetResponse();
                ResponseOk();
            }
            catch (Exception ex)
            {
                Logger.Log.TraceError("RequestEngine.AsyncResponse", ex);
                ResponseError(ex.Message);
            }
            finally
            {
                Tools.Chrono.Stop("RequestEngine");
            }


        }


        #endregion


    }
}
